<?php
//------------------------
// 商品管理模型
//-------------------------
namespace app\common\model;

use think\Model;
use think\Db;
use think\Session;
use think\Cookie;

class Goods extends Model{

    // 获取当前正处在促销期间的商品
	public function getPromoteGoods($limit = 5){
		$now = time();
		return $this->field('id,goods_name,original_price,promote_price,goods_image')
					->where('status',1)
					->where('bargain',1)
					->where('promote_start_time','ELT',$now)
					->where('promote_end_time','EGT',$now)
					->limit($limit)
					->order('promote_end_time')
					->select()
					->toArray();
	}

	// 获取最新商品
	public function getNew($limit = 5){
		return $this->field('id,goods_name,original_price,now_price,goods_image')
					->where('status',1)
					->where('newarrival',1)
				    ->limit($limit)
					->order('create_time')
					->select()
					->toArray();
	}

	// 获取推荐商品
	public function getBest($limit = 5){
		return $this->field('id,goods_name,original_price,now_price,goods_image')
					->where('status',1)
					->where('recommend',1)
				    ->limit($limit)
					->order('create_time')
					->select()
					->toArray();
	}

	// 实时计算会员价格
	public function calculationPrice($goods_id,$old_price){
		// 如果会员没登录直接使用本店价
		$user_id = Session::get('user_id');
		$userRank = Session::get('rank_info');

		if (!$user_id) {
			return $old_price;
		}

		// 计算会员价格
		$user_price = Db('UserRankPrice')->where('goods_id',$goods_id)->where('user_rank_id',$userRank['id'])->field('price')->find();

		if ($user_price) {
			return $user_price['price'];
		} else {
			return $old_price * $userRank['discount_rate'] / 100 ;
		}
	}
}